<div class="noty_bar noty_theme_default noty_layout_topCenter noty_error" id="message_error_top" style="cursor: pointer; left: 559.5px;">
    <div class="noty_message"><span id="message_error_top_text" class="noty_text">Hubo un problema durante la ejecución.</span></div>
</div>

<?php if (isset($success_message)) : ?>
    <div class="noty_bar noty_theme_default noty_layout_topCenter noty_success" id="noty_success_1355937644582" style="cursor: pointer; left: 559.5px; display: block;">
        <div class="noty_message"><span class="noty_text"><?php echo $success_message;?></span></div>
    </div>
<?php endif; ?>

<div class="grid_container">

    <form id="formAddPurchase" action="<?php echo site_url("sales/submit");?>" method="post" class="form_container">
        <input type="hidden" name="id_sale" value="<?php if(isset($sale)) echo $sale->id_sale; ?>">
		<div class="grid_12">
            <div class="widget_wrap">
                <div class="widget_top">
                    <span class="h_icon magnifying_glass"></span>
                    <h6>
						<?php echo $form_title; ?> 
                    </h6>
                </div>

                <div class="widget_content" style="margin-bottom: 30px">
                    <ul>
                        <li>
							<span class="label_head"></span>
                            <div class="form_grid_12">
                                <div class="form_input">
                                    <div class=" form_grid_4 alpha">
                                        <span class="label_head">N° Documento</span>
                                      
                                     <input type="text" name="numero" id="numero" class="noEmpty" value="<?php if(isset($sale)) echo $sale->document_code; ?>" tabindex="2">
                                    </div>
                                   <div class=" form_grid_4 alpha">
                                        <span class="label_head">Fecha</span>
                                        <input type="text" name="date"  id="numero" value="<?php if(isset($sale)){ echo $sale->date;} else { echo date('d/m/Y');} ?>" tabindex="3">
                                    </div>
                                    <span class="clear"></span>
                                </div>
                            </div>
                        </li>
                        <li>
                            <div class="form_grid_12">
                                <div class="form_input">
                                    <div class="form_grid_5 alpha">
                                        <span class="label_head">Cliente</span>
                                        <?php
                                        $options = array();
                                        $options[0] = "";
                                        foreach ($clients as $td) {
                                            $options[$td->id] = $td->name;
                                        }

                                        $extra = 'id="client" tabindex="3" style="width:340px" class="chzn-select full" data-placeholder="Elegir..."';

										$id_cliente_de_guia = '';
										if(isset($sale)) $id_cliente_de_guia = $sale->id_client;
                                        echo form_dropdown('client', $options, $id_cliente_de_guia, $extra);
                                        ?>
                                        <a href="#" class="basic-modal">Nuevo</a>
                                    </div>                                  
                                    <span class="clear"></span>
                                </div>
                            </div>
                        </li>
                        <li>
                           <div class="form_grid_12">
                                <div class="form_input">
                                    <div class="form_grid_8 alpha">
                                        <span class="label_head">Observaciones</span>
                                        <input type="text" name="observations" id="observations" tabindex="5" value="<?php if (isset($sale)) echo $sale->observations;?>">
                                    </div>
                                    <span class="clear"></span>
                                </div>
                            </div>
                        </li>
                    </ul>

					<script>
						function calcular_total_guia(){
							$('#subtotalgeneral').val(0);
							
							$('#table_details tr').each(function (i) {
								var total_subtotalcost = $(this).find("input[name*=subtotal]").val();
								
								if(total_subtotalcost != undefined){
									total_subtotalcost = total_subtotalcost.replace(",","");
									var total_guia = $('#subtotalgeneral').val();
									
									if(total_guia == '' || total_guia == undefined) total_guia = 0;

									total_guia = parseFloat(total_guia) + parseFloat(total_subtotalcost);
									
									$('#subtotalgeneral').val(parseFloat(total_guia).toFixed(2));
								}
								
								
							});
						}
						$(document).ready(function() {
							$('#addProduct').click(function(e) {
								$.ajax({
									'url': url + '/product_selection_modal/',
									'type': 'POST',
									'data': {
										'code': '',
										'description': '',
										'needProductsStock': '1'
									},
									'success': function(res) {
										$('#add-product-model').html(res);
									}
								});
								$('#add-product-model').modal();
								return false;
							});

						})
					</script>

					<div class="form_grid_2 " style="margin-bottom: 10px; float: right">
						<button id="addProduct" class="btn_small btn_blue"><span>Agregar Producto</span></button>
					</div>              

                    <table id="table_details" class="wtbl_list" border="1">
                        <thead>
                            <tr>
                                <th width="10%">Código</th>
                                <th width="30%">Descripción</th>
                                <th width="10%">Cajas</th>
                                <th width="10%">Empaques</th>
                                <th width="10%">Unidades</th>
                                <th width="20%">Subtotal</th>
                                <th width="10%"></th>
                            </tr>

                        </thead>

                        <tbody id="contentProductList">

<?php
	if(isset($saledetails))
    foreach ($saledetails as $sa) {                            
?>
                                <tr>
                                    <td>
                                        <input type="hidden" name="product_id_detalle[]" value="<?php echo $sa->products_id; ?>">
                                        <?php echo $sa->code; ?>
                                    </td>
                                    <td>
                                        <?php echo $sa->description; ?>
                                    </td>
                                    <td align="center">
                                        <input type="hidden" name="totalcaja[]" value="<?php echo $sa->box; ?>">
										<?php echo $sa->box; ?></td>
                                    <td align="center">
                                        <input type="hidden" name="totalpaguete[]" value="<?php echo $sa->pack; ?>">
										<?php echo $sa->pack; ?>
									</td>
                                    <td align="center">
										<input type="hidden" name="totalunidad[]" value="<?php echo $sa->unit; ?>">
										<?php echo $sa->unit; ?>
									</td>
                                    
                                    <td align="center"><input type="hidden" name="subtotal[]" value="<?php echo $sa->amount; ?>">
										<?php echo "US$ ".$sa->amount;   ?></td>
                                    <td align="center">
										<a id="remove-this-row-<?php echo $sa->products_id; ?>" class="action-icons c-Delete">Delete</a>
									
										<?php			
										foreach ($warehouse_distribution as $distribution) {
											if($distribution->product_id == $sa->products_id){
										?>
												<input type="hidden" name="product_id[]" value="<?php echo $distribution->product_id; ?>">
												<input type="hidden" name="code_almacen[]" value="<?php echo $distribution->id_warehouse; ?>">
												<input type="hidden" name="cajas[]" value="<?php echo $distribution->box; ?>">
												<input type="hidden" name="paquetes[]" value="<?php echo $distribution->pack; ?>">
												<input type="hidden" name="unidades[]" value="<?php echo $distribution->unit; ?>">
										<?php
											}
										} ?>
									</td>
                                </tr>
								<script>
									$('#remove-this-row-<?php echo $sa->products_id; ?>').click(function(event) {
										$(this).closest("tr").remove();
										calcular_total_guia();
										return false; 
									});	
								</script>

                        <?php
                            
                        }
                     
                    ?>
                        </tbody>

                    </table>
                    
                    <input type="text" name="subtotalgeneral" id="subtotalgeneral" placeholder="0.00" value="<?php if (isset($sale)){ echo $sale->amount;} ?>" readonly="true" style=" text-align:center; width: 100px; margin-right: 58px; float: right; background: #D0D0D0; font-family: arial; font-size: 15px; font-weight: bold;">
                    <input type="text" value="TOTAL US$" readonly="true" style=" text-align:right; width: 100px; float: right; background: #D0D0D0; font-family: arial; font-size: 15px; font-weight: bold;">
                </div>
            </div>
            <br />

                <script type="text/javascript">
                    $(document).ready(function() {
                        
                        function checkCode() {

                            $.ajax({
                                'url': url + '/sales/search_code_unique',
                                'type': 'POST',
                                'data': {'numero': $('input[name=numero]').val()},
                                'success': function(res) {
                                    //alert("alert res: " + res);
                                    if (res == 1) {

                                        alert('El código del documento ya fue ingresado anteriormente al sistema.');
                                        $('#numero').css('background', '#ff3333');

                                    } else if (res == 0) {


                                        $('#numero').css('background', '#ffffff');
                                        $('#formAddPurchase').submit();
                                    }
                                }
                            });

                        }

                        $('#numero').focus(function() {
                            $('#numero').css('background', '#ffffff');
                        })
                        $('input[name=date]').focus(function() {
                            $('input[name=date]').css('background', '#ffffff');
                        })


                        function formtrue() {
                            $('formAddPurchase').submit(function() {
                                return true;
                            });
                        }
                        function formfalse() {
                            $('formAddPurchase').submit(function() {
                                return false;
                            });
                        }

                        $('#guardar_guia').click(function() {
                            var codigo = $('#numero').val();
							var fecha = $('input[name=date]').val();
							var filas_en_detalle = $('#table_details tr').length;
							
							if (codigo.length < 1 || codigo == ''){
								$('div[id=message_error_top]').css('display', 'block');
								$('span[id=message_error_top_text]').html('Ingrese el número de documento.');
							} else if (fecha.length < 1 || fecha == ''){
								$('div[id=message_error_top]').css('display', 'block');
								$('span[id=message_error_top_text]').html('Ingrese la fecha.');
							} else if(filas_en_detalle < 2){
								$('div[id=message_error_top]').css('display', 'block');
								$('span[id=message_error_top_text]').html('Debe agregar algún producto');
							} else {
								<?php if(isset($sale)){?>
										$('#formAddPurchase').submit();
								<?php }else{ ?>
										checkCode();
								<?php } ?>
								
                            } 
                        });
                                               
                    })
                </script>
                
                    <button type="button" id="guardar_guia" class="btn_small btn_orange"><span>Guardar</span></button>
                               
                            


        </div>
    </form>
    <span class="clear"></span>

    <div id="basic-modal-content">
        <script>
                                        $(document).ready(function() {
                                            $('#name').focus(function() {
                                                $('#boton_guardar_cliente').click();
                                              });
                                            $('#name').focus();                                                                       
                                            $('#boton_guardar_cliente').click(function(e) {
                                                var name = $('#name').val();
                                                var ruc = $('#ruc').val();
                                                var address = $('#address').val();
                                                var telephone = $('#telephone').val();
                                                var email = $('#email').val();                                                                                                                        
                                            $("#formAddClient").validate({
                                            rules: {
                                                name: {           //input name: fullName
                                                    required: true  //required boolean: true/false                                             
                                                },
                                                ruc: {           //input name: fullName
                                                    numeric: true  //required boolean: true/false                                             
                                                },
                                                telephone: {           //input name: fullName
                                                    numeric: true  //required boolean: true/false                                             
                                                },
                                                email: {            //input name: message                                       
                                                    email : true
                                                }
                                            },
                                            messages: {               //messages to appear on error
                                                name: {
                                                      required:"Debe ingresar su nombre"                                         
                                                      },
                                                ruc: {
                                                      numeric:"Debe ingresar sólo números"                                         
                                                      }, 
                                                telephone: {
                                                      numeric:"Debe ingresar sólo números"                                         
                                                      }, 
                                                email: {
                                                      email: "Introducir una dirección de correo válido"                                         
                                                      }
                                            }
                              
                           });
                           
                           
                                            });                                                                                        
                                        })
                                    </script> 
        <h3>Nuevo Cliente</h3>
        <form id="formAddClient" method="post" action="<?php echo base_url(); ?>index.php/clients/add" class="form_container left_label">
            <ul>
                <li>
                    <div class="form_grid_12">
                        <label class="field_title" for="rs">Razón Social <span class="req">*</span></label>
                        <div class="form_input">
                            <input type="text" id="name" name="name" value="<?php echo @field($client->name, set_value('name')); ?>" class="noEmpty" tabindex="20">
                            
                        </div>
                    </div>
                </li>
                <li>
                    <div class="form_grid_12">
                        <label class="field_title" for="ruc">RUC</label>
                        <div class="form_input">
                            <?php
                            $data = array(
                                'name' => 'ruc',
                                'id' => 'ruc',
                                'class' => 'onlyNumber',
                                'maxlength' => 11,
                                'value' => @field($client->ruc, set_value('ruc')),
                                'tabindex' => '21'
                            );
                            echo form_input($data);
                            ?>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="form_grid_12">
                        <label class="field_title">Dirección</label>
                        <div class="form_input">
                            <?php
                            $data = array(
                                'name' => 'address',
                                'id' => 'address',
                                'value' => @field($client->address, set_value('address')),
                                'tabindex' => '22'
                            );
                            echo form_input($data);
                            ?>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="form_grid_12">
                        <label class="field_title">Teléfono</label>
                        <div class="form_input">
                            <?php
                            $data = array(
                                'name' => 'telephone',
                                'id' => 'telephone',
                                'class' => 'onlyNumber',
                                'onkeypress' => 'return isNumberKey(event)',
                                'value' => @field($client->telephone, set_value('telephone')),
                                'tabindex' => '23'
                            );
                            echo form_input($data);
                            ?>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="form_grid_12">
                        <label class="field_title">E-mail</label>
                        <div class="form_input">
                            <input type="text" name="email" id="email" class="email" value="<?php echo @field($client->email, set_value('email')); ?>" tabindex="24" placeholder="Email@4dominio.com">

                        </div>
                    </div>
                </li>
                <li>
                    <div class="form_grid_12">
                        <script>
                           
                        </script>
                        <button type="submit" class="btn_small btn_orange" id="boton_guardar_cliente"><span>Guardar</span></button>
                    </div>
                </li>
            </ul>
        </form>
    </div>
    <div id="add-product-model">
    </div>
</div>

<table id="listProductBlank" class="clear">
    <tr id="rowListProductBlank" class="tr_even">
        <td class="elementList codeProduct"></td>
        <td class="elementList descriptionProduct"></td>
        <td class="elementList quantityBoxesProduct"></td>
        <td class="elementList quantityPackagesProduct"></td>
        <td class="elementList quantityUnitsProduct"></td>
        <td class="elementList priceProduct"></td>
        <td class="elementList inputProduct"><a href="#" class="action-icons c-Delete delProductList" original-title="Borrar">Delete</a></td>
    </tr>
</table>